<template>
  <view class="points-container">
    <!-- 顶部功德分概览卡片 -->
    <view class="points-card">
      <view class="points-bg"></view>
      <view class="points-header">
        <view class="points-title">我的功德分</view>
        <view class="points-value">{{ points }}</view>
      </view>
      <view class="points-stats">
        <view class="stat-item">
          <text class="stat-value">{{ monthPoints }}</text>
          <text class="stat-label">本月获得</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="stat-value">{{ usedPoints }}</text>
          <text class="stat-label">已使用</text>
        </view>
      </view>
      <view class="points-action">
        <!--       <view class="action-btn" @tap="navigateTo('/pages/points/detail')">功德分明细</view>
        <view class="action-btn" @tap="navigateTo('/pages/points/rules')">功德分规则</view> -->
      </view>
    </view>

    <!-- 功德分兑换分类 -->
    <view class="exchange-tabs">
      <!-- <view 
        class="tab-item" 
        :class="{active: currentTab === 'all'}" 
        @tap="switchTab('all')"
      >全部</view> -->
      <view
        class="tab-item"
        :class="{ active: currentTab === 'points' }"
        @tap="switchTab('points')"
        >功德分兑换</view
      >
      <!-- <view 
        class="tab-item" 
        :class="{active: currentTab === 'mixed'}" 
        @tap="switchTab('mixed')"
      >功德分+金额</view> -->
    </view>

    <!-- 商品列表 -->
    <view class="exchange-list">
      <view
        class="exchange-item"
        v-for="(item, index) in filteredProducts"
        :key="index"
        @tap="showProductDetail(item)"
      >
        <image
          class="item-image"
          :src="item.product.image[0].file_path || ''"
        ></image>
        <view class="item-info">
          <view class="item-name">{{ item.product.product_name }}</view>
          <view class="item-tags">
            <view class="tag" v-if="item.isNew">新品</view>
            <view class="tag" v-if="item.isHot">热门</view>
            <view class="tag">限量</view>
          </view>
          <view class="item-price">
            <text class="price-points">{{ item.points }}功德分</text>
            <!-- <text class="price-money" v-if="item.point_price > 0"
              >¥{{ item.point_price }}</text
            > -->
          </view>
        </view>
        <view class="exchange-action-wrap">
          <view class="exchange-btn">立即兑换</view>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view class="list-footer" v-if="filteredProducts.length > 0">
      <text>—— 已经到底啦 ——</text>
    </view>

    <view class="empty-list" v-if="filteredProducts.length === 0">
      <image class="empty-icon" src="/static/icons/empty-box.png"></image>
      <text>暂无可兑换商品</text>
    </view>

    <!-- 商品详情弹窗 -->
    <view class="product-modal" v-if="showModal">
      <view class="modal-mask" @tap="hideProductDetail"></view>
      <view class="modal-content">
        <view class="modal-close" @tap="hideProductDetail">×</view>

        <view class="product-detail">
          <swiper class="product-swiper" indicator-dots autoplay circular>
            <swiper-item
              v-for="(img, imgIndex) in selectedProduct.product.image"
              :key="imgIndex"
            >
              <image :src="img.file_path" mode="aspectFill"></image>
            </swiper-item>
          </swiper>

          <view class="product-info">
            <view class="product-name">{{
              selectedProduct.product.product_name
            }}</view>
            <view class="product-price">
              <text class="price-points"
                >{{ selectedProduct.points }}功德分</text
              >
              <!-- <text class="price-plus" v-if="selectedProduct.price > 0">+</text>
              <text class="price-money" v-if="selectedProduct.price > 0"
                >¥{{ selectedProduct.price.toFixed(2) }}</text
              >-->
              <view class="product-stock"
                >库存:{{ selectedProduct.product.product_stock }}件</view
              >
            </view>

            <view class="product-desc">
              <view class="desc-title">商品介绍</view>
              <text class="desc-content">{{
                selectedProduct.product.selling_point
              }}</text>
            </view>

            <!-- 选择数量 -->
            <view class="product-quantity">
              <view class="quantity-title">兑换数量</view>
              <view class="quantity-selector">
                <view class="quantity-btn" @tap="decreaseQuantity">-</view>
                <input
                  type="number"
                  class="quantity-input"
                  v-model="exchangeQuantity"
                />
                <view class="quantity-btn" @tap="increaseQuantity">+</view>
              </view>
            </view>
            <!-- 收货地址 -->
            <view class="address-section" @tap="chooseAddress">
              <view class="address-title">收货地址</view>
              <view class="address-content" v-if="address">
                <view class="address-info">
                  <view class="user-info">
                    <text class="username">{{ address.name }}</text>
                    <text class="phone">{{ address.phone }}</text>
                    <text class="address-tag" v-if="address.customTagText">{{
                      address.customTagText
                    }}</text>
                  </view>
                  <view class="address-detail">
                    <text class="address-text"
                      >{{ address.region?.province }}{{ address.region?.city
                      }}{{ address.region?.region }}{{ address.detail }}</text
                    >
                  </view>
                </view>
              </view>
              <view class="address-content" v-else>
                <text>请选择收货地址</text>
              </view>
              <view class="address-right">
                <uni-icons type="right"></uni-icons>
              </view>
              <view class="address-divider"></view>
            </view>
            <!-- 总计 -->
            <view class="exchange-total">
              <text>合计:</text>
              <text class="total-points">{{ totalPoints }}功德分</text>
              <!-- <text class="total-plus" v-if="totalPrice > 0">+</text>
              <text class="total-money" v-if="totalPrice > 0"
                >¥{{ totalPrice.toFixed(2) }}</text
              > -->
            </view>
          </view>

          <!-- 兑换按钮 -->
          <view class="exchange-action">
            <view class="insufficient" v-if="points < totalPoints">
              <text>功德分不足，还差{{ totalPoints - points }}功德分</text>
            </view>
            <button
              class="exchange-confirm-btn"
              :disabled="
                points < totalPoints || selectedProduct.stock < exchangeQuantity
              "
              @tap="confirmExchange"
            >
              确认兑换
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 兑换成功弹窗 -->
    <view class="success-modal" v-if="showSuccessModal">
      <view class="success-content">
        <icon type="success" size="64" color="#78A77F"></icon>
        <view class="success-title">兑换成功</view>
        <view class="success-desc">商品已加入"我的订单"</view>
        <view class="success-btns">
          <button class="success-btn continue" @tap="continueShopping">
            继续兑换
          </button>
          <button class="success-btn order" @tap="viewOrder">查看订单</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { pointProductApi } from "../../api/product";
import { monthPointsApi } from "../../api/user";
import { userStore } from "../../store/userStore";
import { addressListApi } from "../../api/user";
import { addPointOrderApi } from "../../api/order";
const user = userStore(); // 初始化用户状态
export default {
  data() {
    return {
      address: {},
      monthPoints: 0,
      currentTab: "points",
      showModal: false,
      showSuccessModal: false,
      selectedProduct: null,
      exchangeQuantity: 1,
      products: [],
    };
  },
  computed: {
    filteredProducts() {
      if (this.currentTab === "all") {
        return this.products;
      } else if (this.currentTab === "points") {
        //return this.products.filter((item) => item.price === 0);
        return this.products;
      } else {
        return this.products.filter((item) => item.price > 0);
      }
    },
    points() {
      return user.userInfo.points || 0;
    },
    usedPoints() {
      let total = user.userInfo.total_points || 0;
      return total - this.points;
    },
    totalPoints() {
      return this.selectedProduct.points * this.exchangeQuantity;
    },
  },
  onLoad() {
    monthPointsApi().then((res) => {
      this.monthPoints = res.points;
    });
    this.initData();
    //获取默认地址
    addressListApi().then((res) => {
      this.address = res.list[0] || null;
    });
  },
  methods: {
    initData() {
      this.getLists();
    },
    getLists() {
      pointProductApi().then((res) => {
        this.products = res.data;
      });
    },
    // 选择地址
    chooseAddress() {
      uni.showToast({
        title: "为你跳转到至地址页面",
        icon: "none",
      });
      uni.navigateTo({
        url: "/pages/choseaddress/choseaddress?select=1",
      });
    },
    navigateTo(url) {
      uni.navigateTo({
        url: url,
      });
    },

    switchTab(tab) {
      this.currentTab = tab;
    },

    showProductDetail(product) {
      this.selectedProduct = product;
      this.exchangeQuantity = 1;
      this.showModal = true;
    },

    hideProductDetail() {
      this.showModal = false;
      this.selectedProduct = null;
      this.exchangeQuantity = 1;
    },

    decreaseQuantity() {
      if (this.exchangeQuantity > 1) {
        this.exchangeQuantity--;
      }
    },

    increaseQuantity() {
      if (this.exchangeQuantity < this.selectedProduct.product.product_stock) {
        this.exchangeQuantity++;
      } else {
        uni.showToast({
          title: "超出库存数量",
          icon: "none",
        });
      }
    },

    confirmExchange() {
      // 检查功德分是否足够
      if (this.points < this.totalPoints) {
        uni.showToast({
          title: "功德分不足",
          icon: "none",
        });
        return;
      }

      // 检查库存是否足够
      if (this.selectedProduct.product.product_stock < this.exchangeQuantity) {
        uni.showToast({
          title: "库存不足",
          icon: "none",
        });
        return;
      }
		if(!this.address.address_id){
			uni.showToast({
			  title: "请选择收货地址",
			  icon: "none",
			});
			return;
		}
		addPointOrderApi({
			product_id:this.selectedProduct.product_id,
			product_num:this.exchangeQuantity,
			spec_sku_id:"",
			address_id:this.address.address_id,
			is_use_points:1,
			coupon_id: 0,
			remark: '',
		}).then((res)=>{
			user.fetchUserInfo()
			this.showModal = false;
			this.showSuccessModal = true;
		}).catch((error)=>{
			uni.showToast({
			  title: error,
			  icon: "none",
			});
			return;
		})
    },

    continueShopping() {
      this.showSuccessModal = false;
    },

    viewOrder() {
      this.showSuccessModal = false;
      uni.navigateTo({
        url: "/pages/my/order",
      });
    },
  },
};
</script>

<style>
.points-container {
  background-color: #f8f6f1; /* 米白色背景 */
  min-height: 100vh;
  padding-bottom: 50rpx;
}

/* 顶部功德分卡片样式 */
.points-card {
  position: relative;
  margin: 30rpx;
  height: auto;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);
}

.points-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #78a77f, #a5cbb7);
  z-index: 1;
}

.points-header {
  position: relative;
  padding: 30rpx;
  z-index: 2;
}

.points-title {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 10rpx;
}

.points-value {
  font-size: 72rpx;
  color: #ffffff;
  font-weight: bold;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
}

.points-stats {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 20rpx 30rpx;
  background-color: rgba(255, 255, 255, 0.1);
  border-top: 1rpx solid rgba(255, 255, 255, 0.2);
  z-index: 2;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: bold;
  margin-bottom: 6rpx;
}

.stat-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.stat-divider {
  width: 1rpx;
  height: 60rpx;
  background-color: rgba(255, 255, 255, 0.3);
}

.points-action {
  position: relative;
  display: flex;
  justify-content: space-around;
  padding: 0 30rpx 20rpx;
  z-index: 2;
}

.action-btn {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 30rpx;
  padding: 8rpx 30rpx;
  font-size: 24rpx;
  color: #ffffff;
}

/* 功德分兑换分类标签 */
.exchange-tabs {
  display: flex;
  margin: 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #a89b88;
  border-bottom: 4rpx solid transparent;
}

.tab-item.active {
  color: #78a77f;
  border-bottom-color: #78a77f;
  font-weight: bold;
}

/* 商品列表 */
.exchange-list {
  padding: 0 30rpx;
}

.exchange-item {
  display: flex;
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.item-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 28rpx;
  color: #4d3f33;
  margin-bottom: 10rpx;
  font-weight: bold;
}

.item-tags {
  display: flex;
  margin-bottom: 10rpx;
}

.tag {
  font-size: 20rpx;
  color: #ffffff;
  background-color: #e2c675;
  border-radius: 6rpx;
  padding: 2rpx 10rpx;
  margin-right: 10rpx;
}

.tag:nth-child(2) {
  background-color: #78a77f;
}

.tag:nth-child(3) {
  background-color: #e57373;
}

.item-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 20rpx;
}

.price-points {
  font-size: 32rpx;
  color: #78a77f;
  font-weight: bold;
}

.price-plus {
  font-size: 24rpx;
  color: #a89b88;
  margin: 0 6rpx;
}

.price-money {
  font-size: 24rpx;
  color: #e57373;
}

.item-exchange {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exchange-btn {
  background-color: #78a77f;
  color: #ffffff;
  font-size: 24rpx;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
}

.exchange-count {
  font-size: 22rpx;
  color: #a89b88;
}

/* 底部提示 */
.list-footer {
  text-align: center;
  padding: 30rpx 0;
  color: #a89b88;
  font-size: 24rpx;
}

/* 空列表提示 */
.empty-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  color: #a89b88;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

/* 商品详情弹窗 */
.product-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  border-radius: 40rpx 40rpx 0 0;
  max-height: 90vh;
  overflow-y: auto;
  padding-bottom: 50rpx;
}

.modal-close {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.3);
  color: #ffffff;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  z-index: 10;
}

.product-swiper {
  width: 100%;
  height: 500rpx;
}

.product-swiper image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 30rpx;
}

.product-name {
  font-size: 36rpx;
  color: #4d3f33;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.product-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 30rpx;
  position: relative;
}

.product-stock {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 24rpx;
  color: #a89b88;
}

.product-desc {
  background-color: #f8f6f1;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
}

.desc-title {
  font-size: 28rpx;
  color: #4d3f33;
  margin-bottom: 10rpx;
  font-weight: bold;
}

.desc-content {
  font-size: 26rpx;
  color: #a89b88;
  line-height: 1.6;
}

.product-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-top: 1rpx solid #eeeae0;
}

.quantity-title {
  font-size: 28rpx;
  color: #4d3f33;
}

.quantity-selector {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #f8f6f1;
  color: #4d3f33;
  font-size: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
}

.quantity-input {
  width: 80rpx;
  text-align: center;
  font-size: 28rpx;
  margin: 0 10rpx;
}

.exchange-total {
  padding: 20rpx 0;
  text-align: right;
  border-top: 1rpx solid #eeeae0;
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #4d3f33;
}

.total-points {
  font-size: 32rpx;
  color: #78a77f;
  font-weight: bold;
  margin-left: 10rpx;
}

.total-plus {
  margin: 0 6rpx;
}

.total-money {
  color: #e57373;
}

.exchange-action {
  padding: 30rpx;
  padding-top: 0;
}

.insufficient {
  text-align: center;
  color: #e57373;
  font-size: 24rpx;
  margin-bottom: 20rpx;
}

.exchange-confirm-btn {
  background-color: #78a77f;
  color: #ffffff;
  border-radius: 50rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}

.exchange-confirm-btn[disabled] {
  background-color: #cccccc;
  color: #ffffff;
}

/* 兑换成功弹窗 */
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 101;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
}

.success-content {
  background-color: #ffffff;
  width: 560rpx;
  padding: 50rpx 30rpx;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-title {
  font-size: 36rpx;
  color: #4d3f33;
  margin: 20rpx 0 10rpx;
  font-weight: bold;
}

.success-desc {
  font-size: 28rpx;
  color: #a89b88;
  margin-bottom: 40rpx;
}

.success-btns {
  display: flex;
  width: 100%;
}

.success-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin: 0 10rpx;
}

.continue {
  background-color: #f8f6f1;
  color: #4d3f33;
}

.order {
  background-color: #78a77f;
  color: #ffffff;
}
/* 收货地址样式 */
.address-section {
  margin: 20rpx 0;
  position: relative;
  display: flex;
  padding-top: 30rpx;
  /* box-shadow: 0 5rpx 15rpx rgba(106, 76, 41, 0.3); */
  border-top: 1px solid #eeeae0;
}

.address-content {
  flex: 1;
  font-size: 28rpx;
}
.address-title {
  color: #4d3f33;
  font-size: 28rpx;
  width: 120rpx;
}
</style>
